<?php

namespace Controller\Category;

class AddCategory extends \Controller\Base {

	public function actionIndex() {
		if ($this->isPost()) {
			$this->doSave();
		}
		$this->setMenuPath('Article', 'Category');
        $pid = $this->getInt('pid');
        $pid = $pid ? $pid : null;
        if ($pid) {
            $this->setMenuPath('Category_' . $pid, 'Category');
        }
        $all = \Data\Category::instance()->getLevelCategories(0, $pid);
        $id = $this->getInt('id');
		if ($id) {
			$category = \Data\Category::instance()->getCategoryById($id);
			if (!$category) {
				$this->throwException('分类不存在');
			}
			$this->assign('category', $category);
		}
		$this->assign('all', $all);
		$this->assign('pid', $pid);
		$this->display();
	}

	public function doSave() {
		$pid = $this->postInt('pid');
		$sort = $this->postInt('sort');
		$type = $this->postInt('type');
		$name = $this->postParam('name');
		if (!$name) {
			$this->addErrorMsg('请填写分类名称');
			return;
		}
		if ($pid) {
			$pInfo = \Data\Category::instance()->getCategoryById($pid);
			if (!$pInfo) {
				$this->addErrorMsg('请选择正确的上级分类');
				return;
			}
		}
		$data = array(
			'CategoryName' => $name,
			'Pid' => $pid,
			'Sort' => $sort,
			'Type' => $type,
		);
		$id = $this->postInt('id');
		if ($id) {
			if (!\Data\Category::instance()->getCategoryById($id)) {
				$this->throwException('分类不存在');
			}
			\Data\Category::instance()->updateById($data, $id);
		} else {
			if (\Data\Category::instance()->getCategoryByName($name)) {
				$this->addErrorMsg('这个分类名称已经存在');
				return;
			}
			\Data\Category::instance()->add($data);
		}
		$this->addSuccessMsg('保持成功');
	}
}